package com.zw.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class DirectServiceAccessFilter extends ZuulFilter {

    private static final String SERVICE_ID = "consumer"; // 替换为你的服务ID
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        // 检查是否为直接访问服务，不通过Zuul
        System.out.println(request.getRequestURI());
        boolean directAccess = request.getRequestURI().contains("/" + SERVICE_ID + "/");
        return !directAccess;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        ctx.setSendZuulResponse(false); // 不允许直接访问，返回403禁止访问
        ctx.setResponseStatusCode(403);
        return null;
    }
}
